// memory-game.js - 记忆翻牌游戏逻辑
const { playRightSound, playWrongSound, playClickSound } = require('../../../../utils/audioUtils.js');
const storageManager = require('../../../../manager/storageManager').getInstance();

Page({
  data: {
    cards: [],
    flippedCards: [],
    matchedPairs: 0,
    totalPairs: 6,
    moves: 0,
    timeElapsed: 0,
    gameStarted: false,
    gameOver: false,
    resultIcon: '',
    resultTitle: '',
    stars: 0,
    accuracy: 0,
    showToast: false,
    toastMessage: '',
    toastIcon: '',
    toastBg: '#4caf50',
    canFlip: true
  },

  onLoad: function() {
    // 初始化数据管理器 - 使用全局实例
    const app = getApp();
    this.wordDataManager = app.globalData.wordDataManager;
    this.magicCoinManager = app.getMagicCoinManager();
    this.timer = null;
    this.initGame();
  },

  onUnload: function() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },

  // 初始化游戏
  initGame: function() {
    const words = this.getRandomWords(6);
    const cards = this.createCards(words);
    
    this.setData({
      cards,
      flippedCards: [],
      matchedPairs: 0,
      moves: 0,
      timeElapsed: 0,
      gameStarted: false,
      gameOver: false,
      canFlip: false // 初始状态不允许翻牌
    });

    if (this.timer) {
      clearInterval(this.timer);
    }
    
    // 开始初始展示卡片的动画
    this.showAllCardsInitially();
  },
  
  // 初始逐一翻开所有卡片
  showAllCardsInitially: function() {
    const cards = this.data.cards;
    let index = 0;
    
    // 逐一翻开卡片，每100ms翻一张
    const showInterval = setInterval(() => {
      if (index < cards.length) {
        const updatedCards = [...this.data.cards];
        updatedCards[index].flipped = true;
        
        this.setData({
          cards: updatedCards
        });
        
        index++;
      } else {
        clearInterval(showInterval);
        
        // 所有卡片翻开后，显示倒计时提示
        this.showToast('⏱️', '记忆时间：5秒', '#2196F3');
        
        // 5秒后开始逐一盖牌
        setTimeout(() => {
          this.hideAllCardsInitially();
        }, 5000);
      }
    }, 100);
  },
  
  // 初始逐一盖上所有卡片
  hideAllCardsInitially: function() {
    const cards = this.data.cards;
    let index = 0;
    
    // 逐一盖上卡片，每100ms盖一张
    const hideInterval = setInterval(() => {
      if (index < cards.length) {
        const updatedCards = [...this.data.cards];
        updatedCards[index].flipped = false;
        
        this.setData({
          cards: updatedCards
        });
        
        index++;
      } else {
        clearInterval(hideInterval);
        
        // 所有卡片盖上后，允许玩家开始翻牌
        this.setData({
          canFlip: true,
          gameStarted: true
        });
        
        // 开始计时
        this.startTimer();
        
        // 显示游戏开始提示
        this.showToast('🎮', '游戏开始！', '#4caf50');
      }
    }, 100);
  },

  // 获取随机单词
  getRandomWords: function(count) {
    const wordsDict = this.wordDataManager.getAllWords();
    // 将对象转换为数组，并过滤出有效的单词
    const allWords = Object.values(wordsDict).filter(word => word && word.english && word.chinese);
    if (allWords.length === 0) {
      console.error('没有可用的单词');
      return [];
    }
    const shuffled = this.shuffleArray(allWords);
    return shuffled.slice(0, Math.min(count, allWords.length));
  },

  // 创建卡片
  createCards: function(words) {
    const cards = [];
    
    // 为每个单词创建两张卡片：一张英文，一张中文
    words.forEach((word, index) => {
      cards.push({
        id: `word_${index}`,
        pairId: index,
        type: 'word',
        content: word,
        flipped: false,
        matched: false
      });
      
      cards.push({
        id: `translation_${index}`,
        pairId: index,
        type: 'translation',
        content: word,
        flipped: false,
        matched: false
      });
    });

    return this.shuffleArray(cards);
  },

  // 打乱数组
  shuffleArray: function(array) {
    const newArray = [...array];
    for (let i = newArray.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
    }
    return newArray;
  },

  // 翻牌
  flipCard: function(e) {
    // 播放点击音效
    playClickSound();
    
    if (!this.data.canFlip) return;

    const cardId = e.currentTarget.dataset.id;
    const card = this.data.cards.find(c => c.id === cardId);

    // 不能翻已经翻开或已配对的卡片
    if (card.flipped || card.matched) return;

    // 不能翻同一张卡片
    if (this.data.flippedCards.some(c => c.id === cardId)) return;

    // 开始计时
    if (!this.data.gameStarted) {
      this.startTimer();
      this.setData({ gameStarted: true });
    }

    // 翻牌
    const cards = this.data.cards.map(c => 
      c.id === cardId ? { ...c, flipped: true } : c
    );

    const flippedCards = [...this.data.flippedCards, card];

    this.setData({ cards, flippedCards });

    // 如果翻了两张牌，检查是否匹配
    if (flippedCards.length === 2) {
      this.setData({ canFlip: false });
      const moves = this.data.moves + 1;
      this.setData({ moves });

      setTimeout(() => {
        this.checkMatch(flippedCards);
      }, 800);
    }
  },

  // 检查匹配
  checkMatch: function(flippedCards) {
    const [card1, card2] = flippedCards;

    if (card1.pairId === card2.pairId) {
      // 匹配成功
      this.handleMatch(card1, card2);
    } else {
      // 匹配失败
      this.handleMismatch(card1, card2);
    }
  },

  // 处理匹配成功
  handleMatch: function(card1, card2) {
    const cards = this.data.cards.map(c => {
      if (c.id === card1.id || c.id === card2.id) {
        return { ...c, matched: true };
      }
      return c;
    });

    const matchedPairs = this.data.matchedPairs + 1;

    this.setData({
      cards,
      flippedCards: [],
      matchedPairs,
      canFlip: true
    });

    this.showToast('✓', '配对成功！', '#4caf50');

    // 播放成功音效
    playRightSound();
    wx.vibrateShort({ type: 'medium' });

    // 检查是否完成所有配对
    if (matchedPairs === this.data.totalPairs) {
      setTimeout(() => {
        this.endGame();
      }, 500);
    }
  },

  // 处理匹配失败
  handleMismatch: function(card1, card2) {
    const cards = this.data.cards.map(c => {
      if (c.id === card1.id || c.id === card2.id) {
        return { ...c, flipped: false };
      }
      return c;
    });

    this.setData({
      cards,
      flippedCards: [],
      canFlip: true
    });

    this.showToast('✗', '配对失败', '#f44336');

    // 播放失败音效
    playWrongSound();
    wx.vibrateShort({ type: 'heavy' });
  },

  // 开始计时
  startTimer: function() {
    this.timer = setInterval(() => {
      this.setData({
        timeElapsed: this.data.timeElapsed + 1
      });
    }, 1000);
  },

  // 格式化时间
  formatTime: function(seconds) {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    // 使用兼容方式实现两位数格式
    const formattedMins = mins < 10 ? '0' + mins : mins.toString();
    const formattedSecs = secs < 10 ? '0' + secs : secs.toString();
    return formattedMins + ':' + formattedSecs;
  },

  // 显示提示信息
  showToast: function(icon, message, bg) {
    this.setData({
      showToast: true,
      toastIcon: icon,
      toastMessage: message,
      toastBg: bg
    });

    setTimeout(() => {
      this.setData({ showToast: false });
    }, 1000);
  },

  // 结束游戏
  endGame: function() {
    if (this.timer) {
      clearInterval(this.timer);
    }

    // 计算准确率（理想移动次数是配对数）
    const idealMoves = this.data.totalPairs;
    const accuracy = Math.round((idealMoves / this.data.moves) * 100);
    
    let stars = 0;
    let resultIcon = '';
    let resultTitle = '';

    // 根据移动次数和时间评分
    if (this.data.moves <= this.data.totalPairs + 3 && this.data.timeElapsed <= 60) {
      stars = 3;
      resultIcon = '🏆';
      resultTitle = '记忆大师！';
    } else if (this.data.moves <= this.data.totalPairs + 6 && this.data.timeElapsed <= 90) {
      stars = 2;
      resultIcon = '🌟';
      resultTitle = '表现不错！';
    } else {
      stars = 1;
      resultIcon = '👍';
      resultTitle = '继续加油！';
    }

    // 奖励魔法币
    const coins = stars * 10;
    this.magicCoinManager.addMagicCoins(coins, `记忆翻牌游戏 - ${stars}星`);

    // 保存游戏记录
    this.saveGameRecord(stars);

    this.setData({
      gameOver: true,
      accuracy,
      stars,
      resultIcon,
      resultTitle
    });
  },

  // 保存游戏记录
  saveGameRecord: function(stars) {
    try {
      const gameStats = storageManager.getStorage(storageManager.STORAGE_KEYS.WORD_GAME_STATS) || {
        totalGamesPlayed: 0,
        totalStars: 0,
        highScore: 0,
        matching: { played: 0, bestScore: 0 },
        scramble: { played: 0, bestScore: 0 },
        memory: { played: 0, bestScore: 0 }
      };

      const score = Math.max(0, 1000 - (this.data.moves * 10) - (this.data.timeElapsed * 5));

      gameStats.totalGamesPlayed += 1;
      gameStats.totalStars += stars;
      gameStats.highScore = Math.max(gameStats.highScore, score);
      gameStats.memory.played += 1;
      gameStats.memory.bestScore = Math.max(gameStats.memory.bestScore, score);

      storageManager.setStorage(storageManager.STORAGE_KEYS.WORD_GAME_STATS, gameStats);

      const recentGames = storageManager.getStorage(storageManager.STORAGE_KEYS.RECENT_WORD_GAMES) || [];
      recentGames.unshift({
        id: Date.now(),
        gameName: '记忆翻牌',
        icon: '🃏',
        score,
        stars,
        timestamp: new Date().toISOString()
      });

      storageManager.setStorage(storageManager.STORAGE_KEYS.RECENT_WORD_GAMES, recentGames.slice(0, 10));
    } catch (error) {
      console.error('保存游戏记录失败:', error);
    }
  },

  // 重新开始游戏
  restartGame: function() {
    // 播放点击音效
    playClickSound();
    this.initGame();
  },

  // 返回
  goBack: function() {
    // 播放点击音效
    playClickSound();
    
    if (this.timer) {
      clearInterval(this.timer);
    }
    wx.navigateBack();
  },
  
  // 转发给朋友
  onShareAppMessage: function() {
    return {
      title: `我在单词记忆翻牌游戏中用了${this.data.moves}步完成！快来挑战吧！`,
      path: '/pages/challenge/word-games/memory-game/memory-game',
      // imageUrl: '/images/challenge.png'
    };
  },
  
  // 分享到朋友圈
  onShareTimeline: function() {
    return {
      title: `我在单词记忆翻牌游戏中用了${this.data.moves}步完成！快来挑战吧！`,
      query: 'from=timeline',
      // imageUrl: '/images/challenge.png'
    };
  }
});
